package com.kunbo.shop.service.impl.sort;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kunbo.offer.dao.CapabilityParamDao;
import com.kunbo.offer.entity.CapabilityParam;
import com.kunbo.shop.dao.sort.ProductSortDao;
import com.kunbo.shop.entity.sort.ProductSort;
import com.kunbo.shop.service.product.ProductService;
import com.kunbo.shop.service.sort.ProductSortService;
import com.shuohe.util.fitting.FittingUtils;
import com.shuohe.util.json.Json;
import com.shuohe.util.returnBean.ReturnBean;


@Service
public class ProductSortServiceImpl implements ProductSortService{

	@Autowired  ProductSortDao productSortDao;
	
	@Autowired  ProductService productService;
	
	@Autowired  CapabilityParamDao capabilityParamDao;
	
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
	
	@Override
	public ReturnBean insert(ProductSort productSort) {
		// TODO Auto-generated method stub
		productSortDao.save(productSort);
		
		
		
		return new ReturnBean(true,"save success");
	}

	@Override
	@Transactional
	public ReturnBean deleteById(String id) {
		
		ReturnBean r = new ReturnBean(false,"");
		try {
			int ret = 0;
			ReturnBean dr;			
			ret = productSortDao.deleteById(id);
			dr = productService.deleteBySortId(id);
			if(dr.isResult() == false) throw new Exception("概览以及6大详细属性删除失败");
			
			if(ret<0)
			{
				r.setResult(false);
				r.setDescribe("未删除任何概览数据");
			}
			else if(ret==0)
			{
				r.setResult(true);
				r.setDescribe("no delete rows");
			}
			else
			{
				r.setResult(true);
				r.setDescribe("delete "+ret +"rows");
			}					
		}catch(Exception e)
		{
			e.printStackTrace();
			r.setResult(false);
			r.setDescribe("delete fail");
		}
		return r;
	}

	@Override
	public ReturnBean delete(ProductSort productSort) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<ProductSort> getForTree() {
		// TODO Auto-generated method stub
		List<ProductSort> list = productSortDao.findAll();
		System.out.println(Json.toJson(list));
		return getChildsManyGroup(list,"-");
	}

	/**
	 * 根据id返回所有子集分类,(多维List集合,List中含有子集List) 
	 * @author    秦晓宇
	 * @date      2017年1月10日 下午10:40:12 
	 * @param list
	 * @param pid
	 * @return
	 */
	public static List<ProductSort> getChildsManyGroup(List<ProductSort> list,String pid)
	{  
		List<ProductSort> arr = new ArrayList<ProductSort>();  
		for(ProductSort location : list){  
		    if(pid.equals(location.getPid())){  
		        location.setChildren(getChildsManyGroup(list, location.getId()));    
		        arr.add(location);   
		    }  
		}  
		return arr;  
	}

	@Override
	public ProductSort findById(String id) {
		// TODO Auto-generated method stub
		return productSortDao.findById(id);
	}

	@Override
	public List<Map<String,Object>> getFanSelectList(Map<String, Object> map,Map<String, Object> objMap) throws Exception, ScriptException {
		double blowingRate = Double.parseDouble((String) map.get("blowingRate"));//风量
		String state = map.get("state").toString();//风量单位
		if(state.equals("m3/s")){
			blowingRate = blowingRate * 3600;
		}
		String windPressure = map.get("selectWindPresssure").toString();//单选、全压/静压
		double totalHeadQuery = Double.parseDouble((String) map.get("totalHeadQuery"));
		String errorRange = (String) map.get("errorRange");
		double minErrorRange = 0;
		double maxErrorRange = 0;
		String [] arrErrorRange =errorRange.split("~");
		minErrorRange = Double.parseDouble(arrErrorRange[0]);
		maxErrorRange = Double.parseDouble(arrErrorRange[1]);
		//String selectWindPresssure = (String) map.get("selectWindPresssure");
		String sql = "";
		sql += " SELECT";
		sql += " 	f.id,";
		sql += " 	f.productNumber,";
		sql += " 	f.text,op.zhuansu speed,op.midu airDensity,op.yelunzhijing,su.j_yps,su.j_jd ";
		sql += " FROM";
		sql += " 	db_offer_sort f inner JOIN shop_fan_other_param op on f.id = op.fanId left JOIN shop_fan_supplement_param su on f.id = su.fanId";
		sql += " WHERE";
		sql += " 	f.sort_type = 2";
		//转速和空气密度不做为实际的查询参数，只是作为计算实际情况系数所用
		Integer speedQuery = 0;//转速1000r/min
		if(!map.get("speedQuery").equals("") && map.get("speedQuery") != null) {
			speedQuery = Integer.parseInt((String) map.get("speedQuery"));
			//sql +=" and op.zhuansu = '"+speedQuery+"'";
		}
		double airDensityQuery = 0;//空气密度
		if(!map.get("airDensityQuery").equals("")) {
			airDensityQuery = Double.parseDouble((String) map.get("airDensityQuery"));
			//sql +=" and op.midu = '"+airDensityQuery+"'";
		}
		//此处是补充参数的条件
		for(String key : objMap.keySet()){
			if(StringUtils.isNotBlank(objMap.get(key).toString())){
				sql +=" and su."+key+" = '"+objMap.get(key).toString()+"'";
			}
		}
		/*//动态拼接查询参数====风机类型
        if(!map.get("fanType").equals("")) {
        	String fanType = (String) map.get("fanType");
			sql +=" and op.fengjileixing = '"+fanType+"'";
		}*/
        /*if(!map.get("reviseFactor").equals("")) {
        	String reviseFactor = (String) map.get("reviseFactor");
			sql +=" and op.xiuzhengyinsu = '"+reviseFactor+"'";
		}*/
        /*//是否防爆
        if(!map.get("ifExplosionProof").equals("")) {
        	String ifExplosionProof = (String) map.get("ifExplosionProof");
			sql +=" and op.shifufangbao = '"+ifExplosionProof+"'";
		}
        //电压
        if(!map.get("voltage").equals("")) {
        	String voltage =(String) map.get("voltage");
			sql +=" and op.dianya = '"+voltage+"'";
		}
        //频率
        if(!map.get("frequency").equals("")) {
        	String frequency = (String) map.get("frequency");
			sql +=" and op.pinlv = '"+frequency+"'";
		}
        
        //防护等级
        if(!map.get("levelsofprotection").equals("")) {
        	String levelsofprotection = (String) map.get("levelsofprotection");
			sql +=" and op.fanghudengji = '"+levelsofprotection+"'";
		}
        //机壳板厚
        if(!map.get("jikebanhou").equals("")) {
			sql +=" and op.jikebanhou = '"+map.get("jikebanhou").toString()+"'";
		}
        //机壳类型
        if(!map.get("jikeleixing").equals("")) {
			sql +=" and op.jikeleixing = '"+map.get("jikeleixing").toString()+"'";
		}
        //风机安装形式
        if(!map.get("fengjianzhuangxingshi").equals("")) {
        	sql +=" and op.fengjianzhuangxingshi = '"+map.get("fengjianzhuangxingshi").toString()+"'";
		}
        //进口防护网
        if(!map.get("jinkoufanghuwang").equals("")) {
        	sql +=" and op.jinkoufanghuwang = '"+map.get("jinkoufanghuwang").toString()+"'";
		}
        //出口防护网
        if(!map.get("chukoufanghuwang").equals("")) {
			sql +=" and op.chukoufanghuwang = '"+map.get("chukoufanghuwang").toString()+"'";
		}
        // 产品类型
        if(!map.get("productType").equals("")) {
			sql +=" and op.chanpinleixing = '"+map.get("productType").toString()+"'";
		}*/
        
        /*if(!map.get("insulationGrade").equals("")) {
        	String insulationGrade = (String) map.get("insulationGrade");
			sql +=" and op.jueyuandengji = '"+insulationGrade+"'";
		}
       
        if(!map.get("airDuctply").equals("")) {
        	String airDuctply = (String) map.get("airDuctply");
			sql +=" and op.fengtongbanhou = '"+airDuctply+"'";
		}
        
        if(!map.get("airDuctType").equals("")) {
        	String airDuctType = (String) map.get("airDuctType");
			sql +=" and op.fengtongleixing = '"+airDuctType+"'";
		}
        //int aerationType;
        if(!map.get("aerationType").equals("")) {
        	String aerationType = (String) map.get("aerationType");
			sql +=" and op.huanqileixing = '"+aerationType+"'";
		}
       
        if(!map.get("protectiveScreening").equals("")) {
        	String protectiveScreening = (String) map.get("protectiveScreening");
			sql +=" and op.fanghuwang = '"+protectiveScreening+"'";
		}
       
        if(!map.get("authentication").equals("")) {
        	String authentication = (String) map.get("authentication");
			sql +=" and op.renzheng = '"+authentication+"'";
		}*/
        /*//空间加热气
        if(!map.get("spaceHeater").equals("")) {
        	String spaceHeater = (String) map.get("spaceHeater");
			sql +=" and op.kongjianjiareqi = '"+spaceHeater+"'";
		}*/
       System.out.println("执行的sql语句为："+sql);
       List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
       List<Map<String,Object>>  finalMap = new ArrayList<Map<String,Object>> ();
       for (Map<String, Object> map2 : result) {
		String id = (String) map2.get("id");
		System.out.println("id为====="+id);
		System.out.println(map2.get("speed").toString()+"speed==============");
		Integer speed = Integer.parseInt(map2.get("speed").toString());
		double density = Double.parseDouble((String) map2.get("airDensity"));
		ProductSort ps = productSortDao.findOne(id);
		String pcf = ps.getPressureCurveFormula();//获取压力计算公式=======默认是全压计算公式
		if(windPressure.equals("静压")){
			pcf = ps.getStaticCurveFormula();//如果选择静压，改为静压计算公式
		}
		double realityRatio = 1d;
		if(speedQuery != 0){
			double d = Math.pow((double)speedQuery/(double)speed, 2);//此处计算之前必须先进行类型强制转化，不然当分母小于分子时，计算所得数都为0
			System.out.println("转速的2次方的值为："+d);
			realityRatio = (airDensityQuery/density)*d;//风量、压力实际系数
			System.out.println("风压的实际系数为："+realityRatio+"风机id为："+id);
			ps.setPressureRealityRatio(realityRatio);
			productSortDao.save(ps);//将实际的系数更新进入风机模型实体对应的属性中
		}		
		double min=0d;
		try{
			min = ps.getMinFlux();
		}catch(Exception e){}
		
		double max =0d;
		try{
			max = ps.getMaxFlux();
		}catch(Exception e){}
		
		if(min<=blowingRate && blowingRate<=max) {//判断流量是否在性能参数的流量范围之内
			//根据流量计算压力
			if(pcf == null){
				continue;
			}
			ScriptEngineManager manager = new ScriptEngineManager();   
			ScriptEngine engine = manager.getEngineByName("javascript");   	
			Invocable invoke = (Invocable)engine; 
			engine.eval(pcf);
			Double ctp = (Double)invoke.invokeFunction("calculationValue",blowingRate);
			if((100+minErrorRange)/100*ctp*realityRatio<=totalHeadQuery && (100+maxErrorRange)/100*ctp*realityRatio>=totalHeadQuery) {
				finalMap.add(map2);
			}
			System.out.println("计算所得全压 = "+ctp);
			System.out.println("计算所得实际全压 = "+ctp*realityRatio);
		}
		
	   }
		return finalMap;
	}

	@Override
	public List<Map<String,Object>> getFanSelectListEn(Map<String, Object> map) throws Exception, ScriptException {
		double blowingRate = Double.parseDouble((String) map.get("blowingRate"));//风量
		String state = map.get("state").toString();//风量单位
		if(state.equals("m3/s")){
			blowingRate = blowingRate * 3600;
		}
		String windPressure = map.get("selectWindPresssure").toString();//单选、全压/静压
		double totalHeadQuery = Double.parseDouble((String) map.get("totalHeadQuery"));
		String errorRange = (String) map.get("errorRange");
		double minErrorRange = 0;
		double maxErrorRange = 0;
		String [] arrErrorRange =errorRange.split("~");
		minErrorRange = Double.parseDouble(arrErrorRange[0]);
		maxErrorRange = Double.parseDouble(arrErrorRange[1]);
		//String selectWindPresssure = (String) map.get("selectWindPresssure");
		String sql = "";
		sql += " SELECT";
		sql += " 	f.id,";
		sql += " 	f.productNumber,";
		sql += " 	f.text,op.zhuansu speed,op.midu airDensity ";
		sql += " FROM";
		sql += " 	db_offer_sort f inner JOIN shop_fan_other_param op on f.id = op.fanId";
		sql += " WHERE";
		sql += " 	f.sort_type = 2";
		//转速和空气密度不做为实际的查询参数，只是作为计算实际情况系数所用
		Integer speedQuery = 0;//转速1000r/min
		if(!map.get("airDensityQuery").equals("")) {
			speedQuery = Integer.parseInt((String) map.get("speedQuery"));
			//sql +=" and op.zhuansu = '"+speedQuery+"'";
		}
		double airDensityQuery = 0;//空气密度
		if(!map.get("airDensityQuery").equals("")) {
			airDensityQuery = Double.parseDouble((String) map.get("airDensityQuery"));
			//sql +=" and op.midu = '"+airDensityQuery+"'";
		}
		//动态拼接查询参数
        if(!map.get("fanType").equals("")) {
        	String fanType = (String) map.get("fanType");
			sql +=" and op.fengjileixing_en = '"+fanType+"'";
		}
        /*if(!map.get("reviseFactor").equals("")) {
        	String reviseFactor = (String) map.get("reviseFactor");
			sql +=" and op.xiuzhengyinsu_en = '"+reviseFactor+"'";
		}*/
        if(!map.get("ifExplosionProof").equals("")) {
        	String ifExplosionProof = (String) map.get("ifExplosionProof");
			sql +=" and op.shifufangbao_en = '"+ifExplosionProof+"'";
		}
        if(!map.get("voltage").equals("")) {
        	String voltage =(String) map.get("voltage");
			sql +=" and op.dianya = '"+voltage+"'";
		}
        if(!map.get("frequency").equals("")) {
        	String frequency = (String) map.get("frequency");
			sql +=" and op.pinlv = '"+frequency+"'";
		}
        //int levelsofprotection;
        if(!map.get("levelsofprotection").equals("")) {
        	//levelsofprotection = Integer.parseInt((String) map.get("levelsofprotection"));
        	String levelsofprotection = (String) map.get("levelsofprotection");
			sql +=" and op.fanghudengji = '"+levelsofprotection+"'";
		}
        
        
      //防护等级
        if(!map.get("levelsofprotection").equals("")) {
        	String levelsofprotection = (String) map.get("levelsofprotection");
			sql +=" and op.fanghudengji = '"+levelsofprotection+"'";
		}
        //机壳板厚
        if(!map.get("jikebanhou").equals("")) {
			sql +=" and op.jikebanhou_en = '"+map.get("jikebanhou").toString()+"'";
		}
        //机壳类型
        if(!map.get("jikeleixing").equals("")) {
			sql +=" and op.jikeleixing_en = '"+map.get("jikeleixing").toString()+"'";
		}
        //风机安装形式
        if(!map.get("fengjianzhuangxingshi").equals("")) {
        	sql +=" and op.fengjianzhuangxingshi = '"+map.get("fengjianzhuangxingshi").toString()+"'";
		}
        //进口防护网
        if(!map.get("jinkoufanghuwang").equals("")) {
        	sql +=" and op.jinkoufanghuwang_en = '"+map.get("jinkoufanghuwang").toString()+"'";
		}
        //出口防护网
        if(!map.get("chukoufanghuwang").equals("")) {
			sql +=" and op.chukoufanghuwang_en = '"+map.get("chukoufanghuwang").toString()+"'";
		}
        /*//int insulationGrade;
        if(!map.get("insulationGrade").equals("")) {
        	String insulationGrade = (String) map.get("insulationGrade");
			sql +=" and op.jueyuandengji = '"+insulationGrade+"'";
		}
        //int airDuctply;
        if(!map.get("airDuctply").equals("")) {
        	String airDuctply = (String) map.get("airDuctply");
			sql +=" and op.fengtongbanhou_en = '"+airDuctply+"'";
		}
        //int airDuctType;
        if(!map.get("airDuctType").equals("")) {
        	String airDuctType = (String) map.get("airDuctType");
			sql +=" and op.fengtongleixing_en = '"+airDuctType+"'";
		}
        //int aerationType;
        if(!map.get("aerationType").equals("")) {
        	String aerationType = (String) map.get("aerationType");
			sql +=" and op.huanqileixing_en = '"+aerationType+"'";
		}
        //int protectiveScreening;
        if(!map.get("protectiveScreening").equals("")) {
        	String protectiveScreening = (String) map.get("protectiveScreening");
			sql +=" and op.fanghuwang_en = '"+protectiveScreening+"'";
		}
        //int authentication;
        if(!map.get("authentication").equals("")) {
        	String authentication = (String) map.get("authentication");
			sql +=" and op.renzheng = '"+authentication+"'";
		}*/
        //int spaceHeater;
        if(!map.get("spaceHeater").equals("")) {
        	String spaceHeater = (String) map.get("spaceHeater");
			sql +=" and op.kongjianjiareqi_en = '"+spaceHeater+"'";
		}
       System.out.println("执行的sql语句为："+sql);       
       List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
       List<Map<String,Object>>  finalMap = new ArrayList<Map<String,Object>> ();
       for (Map<String, Object> map2 : result) {
		String id = (String) map2.get("id");
		System.out.println("id为====="+id);
		System.out.println(map2.get("speed").toString()+"speed==============");
		Integer speed = Integer.parseInt(map2.get("speed").toString());
		double density = Double.parseDouble((String) map2.get("airDensity"));
		ProductSort ps = productSortDao.findOne(id);
		String pcf = ps.getPressureCurveFormula();//获取压力计算公式
		if(windPressure.equals("静压")){
			pcf = ps.getStaticCurveFormula();//如果选择静压，改为静压计算公式
		}
		double d = Math.pow((double)speedQuery/(double)speed, 2);//此处计算之前必须先进行类型强制转化，不然当分母小于分子时，计算所得数都为0
		System.out.println("转速的2次方的值为："+d);
		double realityRatio = (airDensityQuery/density)*d;//风量、压力实际系数
		System.out.println("风压的实际系数为："+realityRatio+"风机id为："+id);
		ps.setPressureRealityRatio(realityRatio);
		productSortDao.save(ps);//将实际的系数更新进入风机模型实体对应的属性中
		double min=0d;
		try{
			min = ps.getMinFlux();
		}catch(Exception e){}
		
		double max =0d;
		try{
			max = ps.getMaxFlux();
		}catch(Exception e){}
		
		if(min<=blowingRate && blowingRate<=max) {//判断流量是否在性能参数的流量范围之内
			//根据流量计算压力
			ScriptEngineManager manager = new ScriptEngineManager();   
			ScriptEngine engine = manager.getEngineByName("javascript");   	
			Invocable invoke = (Invocable)engine; 
			engine.eval(pcf);
			Double ctp = (Double)invoke.invokeFunction("calculationValue",blowingRate);
			if((100+minErrorRange)/100*ctp*realityRatio<=totalHeadQuery && (100+maxErrorRange)/100*ctp*realityRatio>=totalHeadQuery) {
				finalMap.add(map2);
			}
			System.out.println("计算所得全压 = "+ctp);
			System.out.println("计算所得实际全压 = "+ctp*realityRatio);
		}
		
	   }
		return finalMap;
	}
	@Override
	public List<ProductSort> getSortTree() {
		// TODO Auto-generated method stub
		List<ProductSort> list = productSortDao.findNoProduct();
		System.out.println(Json.toJson(list));
		return getChildsManyGroupForSort(list,"-");
	}
	public static List<ProductSort> getChildsManyGroupForSort(List<ProductSort> list,String pid)
	{  
		List<ProductSort> arr = new ArrayList<ProductSort>();  
		for(ProductSort location : list){  
		    if(pid.equals(location.getPid())){  
		        location.setChildren(getChildsManyGroup(list, location.getId()));    
		        arr.add(location);   
		    }  
		}  
		return arr;  
	}

	@Override
	public ProductSort getParentById(String id) {
		ProductSort nowProductSort = productSortDao.findById(id);
		ProductSort parentProductSort = productSortDao.findById(nowProductSort.getPid());
		return parentProductSort;
	}

	@Override
	public List<Map<String, Object>> getFanSelectList2(Map<String, Object> map,Map<String, Object> objMap)
			throws Exception, ScriptException {
		double blowingRate = Double.parseDouble((String) map.get("blowingRate"));//风量
		String state = map.get("state").toString();//风量单位
		if(state.equals("m3/s")){
			blowingRate = blowingRate * 3600;
		}
		String windPressure = map.get("selectWindPresssure").toString();//单选、全压/静压
		double totalHeadQuery = Double.parseDouble((String) map.get("totalHeadQuery"));//全压/静压数值
		String errorRange = (String) map.get("errorRange");
		double minErrorRange = 0;
		double maxErrorRange = 0;
		String [] arrErrorRange =errorRange.split("~");
		minErrorRange = Double.parseDouble(arrErrorRange[0]);//误差--最小值
		maxErrorRange = Double.parseDouble(arrErrorRange[1]);//误差--最大值
		//转速和空气密度不做为实际的查询参数，只是作为计算实际情况系数所用
		Integer speedQuery = 0;//转速1000r/min
		if(!map.get("speedQuery").equals("")) {
			speedQuery = Integer.parseInt((String) map.get("speedQuery"));
		}
		double airDensityQuery = 0;//空气密度
		if(!map.get("airDensityQuery").equals("")) {
			airDensityQuery = Double.parseDouble((String) map.get("airDensityQuery"));
		}
		String sql = "";
		sql += " SELECT";
		sql += " 	f.id,";
		sql += " 	f.productNumber,";
		sql += " 	f.text,op.zhuansu speed,op.midu airDensity,op.yelunzhijing,su.j_yps,su.j_jd ";
		sql += " FROM";
		sql += " 	db_offer_sort f inner JOIN shop_fan_other_param op on f.id = op.fanId left JOIN shop_fan_supplement_param su on f.id = su.fanId";
		sql += " WHERE";
		sql += " 	f.sort_type = 2";
		//此处是补充参数的条件
		for(String key : objMap.keySet()){
			if(StringUtils.isNotBlank(objMap.get(key).toString())){
				sql +=" and su."+key+" = '"+objMap.get(key).toString()+"'";
			}
		}
		/*//动态拼接查询参数====风机类型
        if(!map.get("fanType").equals("")) {
        	String fanType = (String) map.get("fanType");
			sql +=" and op.fengjileixing = '"+fanType+"'";
		}
        //是否防爆
        if(!map.get("ifExplosionProof").equals("")) {
        	String ifExplosionProof = (String) map.get("ifExplosionProof");
			sql +=" and op.shifufangbao = '"+ifExplosionProof+"'";
		}
        //电压
        if(!map.get("voltage").equals("")) {
        	String voltage =(String) map.get("voltage");
			sql +=" and op.dianya = '"+voltage+"'";
		}
        //频率
        if(!map.get("frequency").equals("")) {
        	String frequency = (String) map.get("frequency");
			sql +=" and op.pinlv = '"+frequency+"'";
		}
        //防护等级
        if(!map.get("levelsofprotection").equals("")) {
        	String levelsofprotection = (String) map.get("levelsofprotection");
			sql +=" and op.fanghudengji = '"+levelsofprotection+"'";
		}
        //机壳板厚
        if(!map.get("jikebanhou").equals("")) {
			sql +=" and op.jikebanhou = '"+map.get("jikebanhou").toString()+"'";
		}
        //机壳类型
        if(!map.get("jikeleixing").equals("")) {
			sql +=" and op.jikeleixing = '"+map.get("jikeleixing").toString()+"'";
		}
        //风机安装形式
        if(!map.get("fengjianzhuangxingshi").equals("")) {
        	sql +=" and op.fengjianzhuangxingshi = '"+map.get("fengjianzhuangxingshi").toString()+"'";
		}
        //进口防护网
        if(!map.get("jinkoufanghuwang").equals("")) {
        	sql +=" and op.jinkoufanghuwang = '"+map.get("jinkoufanghuwang").toString()+"'";
		}
        //出口防护网
        if(!map.get("chukoufanghuwang").equals("")) {
			sql +=" and op.chukoufanghuwang = '"+map.get("chukoufanghuwang").toString()+"'";
		}
        //空间加热气
        if(!map.get("spaceHeater").equals("")) {
        	String spaceHeater = (String) map.get("spaceHeater");
			sql +=" and op.kongjianjiareqi = '"+spaceHeater+"'";
		}
        // 产品类型
        if(!map.get("productType").equals("")) {
			sql +=" and op.chanpinleixing = '"+map.get("productType").toString()+"'";
		}*/
       //System.out.println("执行的sql语句为："+sql);
       List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
       List<Map<String,Object>>  finalMap = new ArrayList<Map<String,Object>> ();
       
       //第一步，求比转速
       double bizhuangsu = 5.54 * speedQuery * Math.pow((double)blowingRate/3600, 0.5) / Math.pow((1.2/airDensityQuery) * totalHeadQuery,0.75);
       System.err.println("比转速="+bizhuangsu);
       
       double minYlzj = 0d;////叶轮直径最小值
       if(!map.get("minYlzj").equals("")) {
    	   minYlzj = Double.parseDouble((String) map.get("minYlzj"));
       }
       double maxYlzj = 0d;////叶轮直径最大值
       if(!map.get("maxYlzj").equals("")) {
    	   maxYlzj = Double.parseDouble((String) map.get("maxYlzj"));
       }
       //第二步查询可用数据
       Map<String, Object>  mapTemp = new HashMap<String, Object>();//防止查询不到数据，最终显示效率最高的
       double  tempNum = 0d;//全压效率
       for (Map<String, Object> map2 : result) {
    	   if(map2.get("yelunzhijing") == null || StringUtils.isBlank(map2.get("yelunzhijing").toString())){
    		   continue;
    	   }
    	   if(map2.get("speed")  == null || StringUtils.isBlank(map2.get("speed").toString())){
    		   continue;
    	   }
    	   double tempYlzj = Double.parseDouble(map2.get("yelunzhijing").toString());//库里面的叶轮直径
    	   Integer tempSpeed = Integer.parseInt(map2.get("speed").toString());//库里面的转速
    	   double curYlzj =   Math.pow(tempSpeed *  Math.pow(tempYlzj,3) / speedQuery,1.0/3); //最终的直径
    	   System.err.println("转换后的直径为="+curYlzj);
    	   //第三步，通过  叶轮直径再次过滤
    	   if(minYlzj != 0d && curYlzj < minYlzj){
    		   continue;
    	   }
    	   if(maxYlzj != 0d && curYlzj > maxYlzj){
    		   continue;
    	   }
    	   if(StringUtils.isBlank(map2.get("productNumber").toString())){
    		   continue;
    	   }
    	   //第四步，在明细中进行查询=====(全压比转速、静压的比转速、全压效率)
    	   List<Map<String,Object>> detailList  = jdbcTemplate.queryForList("SELECT fullSpeed,staticSpeed,tProductiveness FROM 	shop_capability_param WHERE fanNumber='"+map2.get("productNumber").toString()+"'");
    	   if(detailList != null && detailList.size() > 0){
    		   for (Map<String, Object> mapDetail : detailList) {
    			   double tempStatic = Double.parseDouble(mapDetail.get("staticSpeed").toString());//临时静压比转速
    			   double tempFull = Double.parseDouble(mapDetail.get("fullSpeed").toString());//临时全压比转速
    			   double tempQYXX = Double.parseDouble(mapDetail.get("tProductiveness").toString());//临时全压效率
    			   if(windPressure.equals("静压")){
    				   if((100+minErrorRange) / 100 * tempStatic <=bizhuangsu && (100+maxErrorRange) / 100 * tempStatic >=bizhuangsu) {
    					   if(tempQYXX > tempNum){
    						   tempNum = tempQYXX;//替换
    						   mapTemp = map2;
    					   }
    					   if(tempQYXX > 50){
    						   if(!finalMap.contains(map2)){
    							   finalMap.add(map2);
    						   }
	    					   continue;
    					   }
    				   }
    			   }else{
    				   if((100+minErrorRange) / 100 * tempFull <=bizhuangsu && (100+maxErrorRange) / 100 * tempFull >=bizhuangsu) {
    					   if(tempQYXX > tempNum){
    						   tempNum = tempQYXX;//替换
    						   mapTemp = map2;
    					   }
    					   if(tempQYXX > 50){
    						   if(!finalMap.contains(map2)){
    							   finalMap.add(map2);
    						   }
	    					   continue;
    					   }
    				   }
    			   }
    		   }
    	   }
       }
       if(finalMap == null || finalMap.size() == 0){
    	   //如果没有，找效率最大的一条
    	   if(mapTemp == null || mapTemp.size() == 0){
    		   return finalMap;
    	   }
    	   finalMap.add(mapTemp);
    	   return finalMap;
       }
       return finalMap;
	}

	@Override
	public List<CapabilityParam> getPerforParam(Map<String, Object> map) {
		double blowingRate = Double.parseDouble((String) map.get("blowingRate"));//风量
		String state = map.get("state").toString();//风量单位
		if(state.equals("m3/s")){
			blowingRate = blowingRate * 3600;
		}
		String windPressure = map.get("selectWindPresssure").toString();//单选、全压/静压
		double totalHeadQuery = Double.parseDouble((String) map.get("totalHeadQuery"));//全压/静压数值
		
		//FittingUtils.getFitting(arrFlux, arrTH, 2);
		Integer speedQuery =  Integer.parseInt((String) map.get("speedQuery"));//输入的转速
		double speedQuery1 = Double.parseDouble(speedQuery.toString());//整形算除法会四舍五入
		
		double airDensityQuery = Double.parseDouble((String) map.get("airDensityQuery"));//输入的空气密度
		String fanNumber = map.get("fanNumber").toString();  //编号---用于取性能参数列表数据
		String fanId = map.get("fanId").toString();//产品ID，用于取其它参数数据
		String sql = "select * from shop_fan_other_param where fanId='" +fanId+ "'";
		Map<String, Object> otherParamMap = jdbcTemplate.queryForMap(sql);// 获取风机其他参数
		double tempYlzj = Double.parseDouble(otherParamMap.get("yelunzhijing").toString());//库里面的叶轮直径
		Integer tempSpeed = Integer.parseInt(otherParamMap.get("zhuansu").toString());//库里面的转速
		double tempSpeed1 = Double.parseDouble(tempSpeed.toString());//整形算除法会四舍五入
		
		double tempMidu = Double.parseDouble(otherParamMap.get("midu").toString());//库里面的密度
		
		//第一步，求比转速
	    double bizhuangsu = 5.54 * speedQuery * Math.pow((double)blowingRate/3600.0, 0.5) / Math.pow((1.2/airDensityQuery) * totalHeadQuery,0.75);
	    System.err.println("比转速="+bizhuangsu);
	    //第二步求出Qe（比转速对应的流量）
	    //先组装两个数据===比转速、流量（先确定是用全压比转速、还是静夺比转速）
	    List<Double> listBzs=new ArrayList<Double>();//比转速
	    List<Double> listLy=new ArrayList<Double>();//流量
	    List<CapabilityParam> list = capabilityParamDao.findByFanNumber(fanNumber);
	    //Double[] array=list.toArray();fullSpeed;//全压比转速 private Double staticSpeed;//静夺比转速
	    
    	for (int i=0;i<list.size();i++) {
    		if(windPressure.equals("静压")){
    			listBzs.add(list.get(i).getStaticSpeed());
    		}else{
    			listBzs.add(list.get(i).getFullSpeed());
    		}
    		listLy.add(list.get(i).getFlux());
        }
    	
    	Double[] arrayX = listBzs.toArray(new Double[listBzs.size()]); 
    	Double[] arrayY =  listLy.toArray(new Double[listLy.size()]); 
    	double tempFlux = 0d;//Qe  数据库里的流量
	    try {
	    	tempFlux = FittingUtils.getFormula(arrayX, arrayY, 2, bizhuangsu);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    System.err.println("比转速===="+bizhuangsu+"，流量========"+tempFlux);
 	    //当前的叶轮直径
 	    //double curYlzj =   Math.pow(tempSpeed *  Math.pow(tempYlzj,3) / speedQuery,1.0/3); //最终的直径 	  
	    double curYlzj =   Math.pow(tempSpeed *  Math.pow(tempYlzj,3) / speedQuery * blowingRate / tempFlux,1.0/3); //最终的直径 	
		//List<CapabilityParam> list = this.capabilityParamDao.findByFanNumber(fanNumber);
		System.err.println("核算出的直径 = （库里的转速 * （库里的直径）3次方  / 输入的转速  * 输入的流量  / 数据库的流量）1/3 次方");
		System.err.println("流量公式=（输入的转速  / 库里的转速 ） * （核算出的直径  / 库里的直径）3次方    *  库里的流量");
		System.err.println("全压公式=（输入的密度  / 库里的密度 ） * （输入的转速  / 库里的转速）2次方  * （核算出的直径  / 库里的直径）2次方    *  库里的全压");
		System.err.println("静压公式=（输入的密度  / 库里的密度 ） * （输入的转速  / 库里的转速）2次方  * （核算出的直径  / 库里的直径）2次方    *  库里的静夺");
		System.err.println("功率公式=（输入的密度  / 库里的密度 ） * （输入的转速  / 库里的转速）3次方  * （核算出的直径  / 库里的直径）5次方    *  库里的功率");
		System.err.println("噪声公式=比A声级 + 10 * log(输入的流量 / 60 * (核算出的全压)2次方 ) - 19.8");
		System.err.println("编号为："+fanNumber+",库里的叶轮直径："+tempYlzj+",变形后的叶轮直径："+(double)Math.round(curYlzj*100)/100+",库里的转速："+tempSpeed+",库里的密度："+tempMidu);
		if(list != null && list.size() > 0){
			for (CapabilityParam capabilityParam : list) {
				System.err.println("库里的流量："+capabilityParam.getFlux()+",库里的全压："+capabilityParam.getTotalHead()+",库里的静夺："+capabilityParam.getStaticPressure()+",库里的功率："+capabilityParam.getInternalPower()+",库里的噪声："+capabilityParam.getNoise());
				//流量修改flux
				double liuL = speedQuery1 / tempSpeed1 * Math.pow(curYlzj / tempYlzj,3) * capabilityParam.getFlux();
				double tliuL = (double)Math.round(liuL*100)/100;
				capabilityParam.setFlux(tliuL);
				//全压修改
				double quanYa = airDensityQuery / tempMidu * (Math.pow(speedQuery1 / tempSpeed1,2)) * (Math.pow(curYlzj / tempYlzj,2)) * capabilityParam.getTotalHead();
				double tquanYa = (double)Math.round(quanYa*100)/100;
				capabilityParam.setTotalHead(tquanYa);
				//静压修改staticPressure
				double jingYa = airDensityQuery / tempMidu * (Math.pow(speedQuery1 / tempSpeed1,2)) * (Math.pow(curYlzj / tempYlzj,2)) * capabilityParam.getStaticPressure();
				double tjingYa = (double)Math.round(jingYa*100)/100;
				capabilityParam.setStaticPressure(tjingYa);
				//功率修改internalPower
				double gongLv = airDensityQuery / tempMidu * (Math.pow(speedQuery1 / tempSpeed1,3)) * (Math.pow(curYlzj / tempYlzj,5)) * capabilityParam.getInternalPower();
				double tgongLv = (double)Math.round(gongLv*100)/100;
				capabilityParam.setInternalPower(tgongLv);
				//噪声noise
				double zaoSheng = capabilityParam.getSoundLevel() + 10 * Math.log(blowingRate / 60.0 * Math.pow(quanYa,2)) - 19.8; 
				double tzaoSheng = (double)Math.round(zaoSheng*100)/100;
				capabilityParam.setNoise(tzaoSheng);	
				//此字段暂时为：直径shaftPower
				double tcurYlzj = (double)Math.round(curYlzj*100)/100;
				capabilityParam.setShaftPower(tcurYlzj);
				//System.err.println("编号为："+fanNumber+",库里的叶轮直径："+tempYlzj+",变形后的叶轮直径："+tcurYlzj+",库里的转速："+tempSpeed+",库里的密度："+tempMidu);
				System.err.println("变形后的流量："+tliuL+",变形后的全压："+tquanYa+",变形后的静夺："+tjingYa+",变形后的功率："+tgongLv+",变形后的噪声："+tzaoSheng);
				
			}
		}
		return list;
	}
	
}
